package JUC;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

public class SemaphoreDemo {

    public static void main(String[] args) {
        Semaphore semaphore = new Semaphore(3);
        for (int i = 1; i <= 6; i++) {
            // 模拟6个车
            new Thread(() -> {
                try {
                    semaphore.acquire();
                    // acquire 得到
                    System.out.println(Thread.currentThread().getName() + " 抢 到了车位");
                    TimeUnit.SECONDS.sleep(3);
                    // 停3秒钟
                    System.out.println(Thread.currentThread().getName() + " 离 开了车位");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    semaphore.release(); // 释放这个位置
                }
            }, String.valueOf(i)).start();
        }
    }
}


